package com.wyait.manage.config.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wyait.manage.entity.ResponseResult;
import com.wyait.manage.utils.IStatusMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


/**
 * 用来解决匿名用户访问无权限资源时的异常
 * @author huangjian
 */
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    private static final Logger LOGGER = LoggerFactory.getLogger(CustomAuthenticationEntryPoint.class);
    private static final ObjectMapper mapper = new ObjectMapper();
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException authException) throws IOException {
        if(isAjaxRequest(request)){
            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            PrintWriter writer = response.getWriter();
            ResponseResult responseResult = new ResponseResult();
            responseResult.setCode(IStatusMessage.SystemStatus.ERROR.getCode());
            responseResult.setMessage("匿名用户，暂无权限访问");
            writer.write(mapper.writeValueAsString(responseResult));
            writer.flush();
            writer.close();
        }else{
            LOGGER.info("匿名用户，暂无权限访问,请先登录");
            response.sendRedirect("/login");
        }
    }

    private boolean isAjaxRequest(HttpServletRequest request) {
        return request.getHeader("X-Requested-With") != null&&request.getHeader("X-Requested-With").equals("XMLHttpRequest");
    }
}